import { ref } from 'vue'
import { defineStore } from 'pinia'
import { userInfoApi } from '@/api'
import { type UserInfoType, IdentityEnum, SexEnum } from '@/api/type'

export const useUserStore = defineStore(
  'user',
  () => {
    // ! Token
    const token = ref<string | null>()

    // ! 定义用户信息
    const user = ref<UserInfoType | null>({
      name: '',
      id: 0,
      identity: IdentityEnum.Student,
      mobile: '',
      account: '',
      avatar: '',
      sex: SexEnum.Male,
      age: '',
      email: '',
      experience: 0,
      signature: '',
    })

    // ! 设置用户登录状态
    function setToken(newToken: string) {
      token.value = newToken
    }

    // ? 定义设置用户信息的函数
    function setUser() {
      userInfoApi().then((res) => {
        user.value = res.data
      })
    }

    // 退出登录
    const logout = () => {
      token.value = null
      user.value = null
    }
    return { token, setToken, user, setUser, logout }
  },
  {
    persist: true,
  },
)
